package com.hoshiicloud.user.controller.store;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hoshiicloud.auth.vo.TokenUsersVO;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.common.utils.BeanUtils;
import com.hoshiicloud.common.utils.token.UserInfoUtil;
import com.hoshiicloud.common.utils.tree.PlatStoreWithPlatStoreTree;
import com.hoshiicloud.user.dto.platform.PlatDTO;
import com.hoshiicloud.user.entity.platform.Platform;
import com.hoshiicloud.user.entity.store.PlatStore;
import com.hoshiicloud.user.param.PlatStoreQueryParam;
import com.hoshiicloud.user.param.store.PlatStoreAddParam;
import com.hoshiicloud.user.param.store.PlatStoreUpdateParam;
import com.hoshiicloud.user.service.platform.PlatformService;
import com.hoshiicloud.user.service.store.PlatStoreService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiSort;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 平台店铺 控制器
 * </p>
 *
 * @author zhangshuhu
 * @since 2019-05-21
 */
@Slf4j
@RestController
@RequestMapping("/store/plat-store")
@Api(value = "租户平台店铺", tags = {"租户平台店铺"})
@ApiSort(41)
public class PlatStoreController {

    @Autowired
    private PlatStoreService platStoreService;

    @Autowired
    private PlatformService platformService;

    /**
     * @param param
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 分页查询平台店铺
     */
    @ApiOperation(value = "分页查询平台店铺")
    @PostMapping("/getPage")
    public Response<Page<PlatStore>> page(@RequestBody PlatStoreQueryParam param) {
        try {
            QueryWrapper<PlatStore> queryWrapper = new QueryWrapper<PlatStore>();
            queryWrapper.lambda()
                    .eq((param.getPlatId() != null), PlatStore::getPlatId, param.getPlatId())
                    .eq((param.getParentId() != null), PlatStore::getParentId, param.getParentId())
                    .eq(StringUtils.isNotBlank(param.getStoreCode()), PlatStore::getStoreCode, param.getStoreCode())
                    .eq((param.getMemberId() != null), PlatStore::getMemberId, param.getMemberId())
                    .like(StringUtils.isNotBlank(param.getStoreName()), PlatStore::getStoreName, param.getStoreName())
                    .eq(StringUtils.isNotBlank(param.getCustomCode()), PlatStore::getCustomCode, param.getCustomCode())
                    .eq(StringUtils.isNotBlank(param.getStoreEname()), PlatStore::getStoreEname, param.getStoreEname())
                    .eq((param.getPlatform() != null), PlatStore::getPlatform, param.getPlatform())
                    .eq((param.getType() != null), PlatStore::getType, param.getType())
                    .eq(StringUtils.isNotBlank(param.getBanner()), PlatStore::getBanner, param.getBanner())
                    .eq(StringUtils.isNotBlank(param.getCharge()), PlatStore::getCharge, param.getCharge())
                    .eq(StringUtils.isNotBlank(param.getIdCard()), PlatStore::getIdCard, param.getIdCard())
                    .eq(StringUtils.isNotBlank(param.getBankNumber()), PlatStore::getBankNumber, param.getBankNumber())
                    .eq(StringUtils.isNotBlank(param.getBankName()), PlatStore::getBankName, param.getBankName())
                    .eq(StringUtils.isNotBlank(param.getBankAddress()), PlatStore::getBankAddress,
                            param.getBankAddress())
                    .eq(StringUtils.isNotBlank(param.getTaxation()), PlatStore::getTaxation, param.getTaxation())
                    .eq(StringUtils.isNotBlank(param.getPiaohao()), PlatStore::getPiaohao, param.getPiaohao())
                    .eq(StringUtils.isNotBlank(param.getTelephone()), PlatStore::getTelephone, param.getTelephone())
                    .eq(StringUtils.isNotBlank(param.getMobile()), PlatStore::getMobile, param.getMobile())
                    .eq(StringUtils.isNotBlank(param.getFax()), PlatStore::getFax, param.getFax())
                    .eq(StringUtils.isNotBlank(param.getHome()), PlatStore::getHome, param.getHome())
                    .eq(StringUtils.isNotBlank(param.getEmail()), PlatStore::getEmail, param.getEmail())
                    .eq(StringUtils.isNotBlank(param.getAddress()), PlatStore::getAddress, param.getAddress())
                    .eq(StringUtils.isNotBlank(param.getGoodsAddress()), PlatStore::getGoodsAddress,
                            param.getGoodsAddress())
                    .eq(StringUtils.isNotBlank(param.getWhouseAddress()), PlatStore::getWhouseAddress,
                            param.getWhouseAddress())
                    .eq((param.getPaymentId() != null), PlatStore::getPaymentId, param.getPaymentId())
                    .eq((param.getDeleted() != null), PlatStore::getDeleted, param.getDeleted());
            Page<PlatStore> page = new Page<>(Long.parseLong(param.getPageNumber()),
                    Long.parseLong(param.getPageSize()));
            String key =
                    param.toString() + ",Page{pageNumber=" + param.getPageNumber() + ",pageSize=" + param.getPageSize()
                            + "}";
            return Response.data(platStoreService.getPage(page, queryWrapper, key));
        } catch (Exception e) {
            log.error("分页查询平台店铺异常", e);
            return Response.failed("分页查询平台店铺异常");
        }

    }

    /**
     * @param id
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 根据id查询平台店铺
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询平台店铺")
    @ApiParam(name = "id", value = "主键ID", required = true)
    public Response<PlatStore> queryById(@PathVariable("id") Long id) {
        return Response.data(platStoreService.getById(id));
    }

    /**
     * @param param
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 新增
     */
    @PostMapping("/save")
    @ApiOperation(value = "新增平台店铺")
    public Response savePlatStore(@RequestBody @Valid PlatStoreAddParam param) {
        PlatStore entity;
        try {
            entity = BeanUtils.covertType(param, PlatStore.class);
        } catch (Exception e) {
            log.error("新增平台店铺Bean转换异常", e);
            return Response.failed("新增平台店铺Bean转换异常");
        }
        return Response.data(platStoreService.save(entity));
    }

    /**
     * @param param
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 修改平台店铺
     */
    @PutMapping("/update")
    @ApiOperation(value = "修改平台店铺")
    public Response updatePlatStoreById(@RequestBody @Valid PlatStoreUpdateParam param) {
        PlatStore entity;
        try {
            entity = BeanUtils.covertType(param, PlatStore.class);
        } catch (Exception e) {
            log.error("修改平台店铺Bean转换异常", e);
            return Response.failed("新增平台店铺Bean转换异常");
        }
        return Response.data(platStoreService.updateById(entity));
    }

    /**
     * @param id
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 删除平台店铺
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "删除平台店铺")
    @ApiParam(name = "id", value = "主键ID", required = true)
    public Response deletePlatStoreById(@PathVariable("id") Long id) {
        return Response.data(platStoreService.deletePlatStoreById(id));
    }

    /**
     * @Author:campchen
     * @Description: StringUtils.join(ids, " ") 为缓存中添加唯一KEY  如不合适可选择更好方法
     * @Date:上午 10:18 2019/5/11
     * @Param: ids
     * @return: com.hoshiicloud.common.rpc.Response
     */
    @ApiOperation(value = "根据id集合查询平台店铺")
    @GetMapping("/getByIds")
    public Response getByIds(@RequestParam List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return Response.failed("获取平台店铺id集合失败");
        }
        ids.sort(null);
        return Response.data(platStoreService.getByIds(ids, StringUtils.join(ids, "")));
    }

    /**
     * 根据平台ID获取店铺列表
     *
     * @param platId 平台ID
     * @return Response<List < PlatStore>>
     */
    @ApiOperation(value = "根据平台ID获取店铺列表")
    @GetMapping("/getStoresByPlatId/{platId}")
    public Response<List<PlatStore>> getStoresByPlatId(@PathVariable("platId") Long platId) {
        return Response.data(platStoreService.getStoresByPlatId(platId));
    }

    /**
     * 批量更新店铺信息
     *
     * @param stores 店铺列表
     * @return Response<List < Long>>
     */
    @ApiOperation(value = "批量更新店铺信息")
    @PostMapping("/batchUpdateStores")
    public Response<List<Long>> batchUpdateStores(@RequestBody List<PlatStore> stores) {
        return Response.data(platStoreService.batchUpdateStores(stores));
    }

    /**
     * 分页查询店铺列表（带距离）
     *
     * @param param 查询参数
     * @return Response<IPage < Map < String, Object>>>
     */
    @ApiOperation(value = "分页查询店铺列表")
    @PostMapping("/storeRange")
    public Response<IPage<Map<String, Object>>> storeRange(@RequestBody PlatStoreQueryParam param) {
        return Response.data(platStoreService.storeRange(param));
    }

    /**
     *
     */
    @GetMapping("/generateCascadingMenu")
    public Response<List<PlatStoreWithPlatStoreTree>> generateCascadingMenu(HttpServletRequest httpServletRequest) {
        TokenUsersVO userInfo = UserInfoUtil.getUserInfo(httpServletRequest);
        Long storeId = userInfo.getStoreId();
        QueryWrapper<PlatStore> platStoreQueryWrapper = new QueryWrapper<>();

        platStoreQueryWrapper.lambda().eq(PlatStore::getParentId, storeId);

        List<PlatStore> platStoreList = platStoreService.list(platStoreQueryWrapper);

        ArrayList<PlatStoreWithPlatStoreTree> platStoreWithPlatStoreTrees = new ArrayList<>(10);

        for (PlatStore platStore : platStoreList) {
            PlatStoreWithPlatStoreTree platStoreWithPlatStoreTree = PlatStoreWithPlatStoreTree.builder()
                    .id(platStore.getId().toString())
                    .parentId(platStore.getParentId() == null ? "" : platStore.getParentId().toString())
                    .value(platStore.getId())
                    .label(platStore.getStoreName())
                    .build();
            platStoreWithPlatStoreTrees.add(platStoreWithPlatStoreTree);
        }

        return Response.data(platStoreWithPlatStoreTrees);
    }


    /**
     * 根据Id判断这个店铺是否为总店
     *
     * @param storeId 店铺ID
     * @return 判断结果
     */
    @GetMapping("/identifyMainStoreById")
    @ApiOperation(value = "根据店铺ID判断这个店铺是否为总店")
    public Response<Boolean> identifyMainStoreById(@RequestParam("storeId") Long storeId) {
        QueryWrapper<PlatStore> platStoreQueryWrapper = new QueryWrapper<>();
        platStoreQueryWrapper.lambda()
                .eq(PlatStore::getId, storeId)
                .select(PlatStore::getParentId);
        PlatStore platStore = platStoreService.getOne(platStoreQueryWrapper);

        if (null == platStore) {
            return Response.data(Boolean.TRUE);
        }

        return Response.data(Boolean.FALSE);
    }

    /**
     * 根据id拿到他的所有分店
     *
     * @param storeId id
     * @return Response
     */
    @GetMapping("/getAllBranchStore")
    @ApiOperation(value = "根据店铺ID拿到这个店铺下面的所有子店")
    public Response<List<PlatStore>> getAllBranchStore(@RequestParam("storeId") Long storeId) {

        PlatStore platStore = platStoreService.getById(storeId);

        return Optional.ofNullable(platStore).map(platStoreRun -> {
            // 判断是否为总店
            Long parentId = platStore.getParentId();
            QueryWrapper<PlatStore> platStoreQueryWrapper = new QueryWrapper<>();

            if (null == parentId) {
                platStoreQueryWrapper.lambda()
                        .eq(PlatStore::getParentId, storeId);
            }
            if (null != parentId) {
                platStoreQueryWrapper.lambda()
                        .eq(PlatStore::getParentId, parentId);
            }

            List<PlatStore> platStoreList = platStoreService.list(platStoreQueryWrapper);
            if (CollectionUtils.isNotEmpty(platStoreList)) {
                return Response.data(platStoreList);
            } else {
                // 避免那边出现空指针异常
                List<PlatStore> emptyList = new ArrayList<>();
                return Response.data(emptyList);
            }

        }).orElseGet(() -> Response.data(new ArrayList<>()));
    }

    /**
     * 获得店铺表, 以及平台表的内容
     */
    @GetMapping("/getStoreAndFormByStoreId")
    public Response<PlatDTO> getStoreAndFormByStoreId(@RequestParam("storeId") Long storeId) {
        PlatStore platStore = platStoreService.getById(storeId);
        Long platId = platStore.getPlatId();
        Platform platform = platformService.getById(platId);
        PlatDTO platDTO = PlatDTO.builder().platStore(platStore)
                .platform(platform)
                .build();
        return Response.data(platDTO);
    }
}
